const Router = require("@koa/router");
const router = new Router();
const { modelAdministrator } = require("@/models/administrator");
const { modelDairecom } = require("@/models/dailyrecom");
const { modelProvince } = require("@/models/chinacity");
const { modelArticle } = require("@/models/article");
const { modelFourTravel } = require("@/models/fourtravel");
const {
  AdminRegister,
  ModifyUserInfor,
  DailyRecom,
  SearchTravel,
  Resreturn,
  CompanionDetails,
  UploadFourTravel,
  ModifyRecomTravel,
} = require("@/validData/pc-admin");
const result = require("@/utils/handle");
const crypto = require("crypto");
const { genToken } = require("@/token/jwt");
const { cosUpdate, upload } = require("@/cos/cos");
const { Auth } = require("@/token/auth");
const fs = require("fs");
const path = require("path");
const { looKup, looKupRecommend } = require("@/config/lookup");
const { modelConcern } = require("@/models/concern");
const { modelUser } = require("@/models/user");

// 注册管理员账号
router.post("/adminRegister", async (ctx) => {
  const { email, password, nickname } = ctx.request.body;
  // 验证数据
  AdminRegister(email, password);
  // 先检查邮箱是否已存在
  const res = await modelAdministrator.find({ email }).lean();
  if (res.length > 0) {
    throw new result("邮箱已存在", 422);
  } else {
    // 创建哈希对象
    const hash = await crypto.createHash("sha256").update(password);
    // 生成哈希值
    const passwordHash = hash.digest("hex");
    // 创建管理员账号
    const admin = await modelAdministrator.create({
      email,
      password: passwordHash,
    });
    ctx.send("SUCCESS", 200, { message: "注册成功" });
  }
});

// 登录
router.post("/adminLogin", async (ctx) => {
  const { email, password } = ctx.request.body;
  AdminRegister(email, password);
  // 创建哈希对象
  const hash = await crypto.createHash("sha256").update(password);
  // 生成哈希值
  const passwordHash = hash.digest("hex");
  // 查询管理员账号
  const res = await modelAdministrator
    .find({ email, password: passwordHash }, { email: false })
    .lean();
  if (res.length > 0) {
    const token = { user_Token: genToken(res[0].admin_uid) };
    ctx.send("SUCCESS", 200, {
      ...res[0],
      ...token,
    });
  } else {
    ctx.send("账号或密码错误", 422);
  }
});

// 图片上传
router.post("/imageUpload", upload.array("file", 6), async (ctx) => {
  const res = await cosUpdate(ctx.files);
  console.log(res);
  ctx.send("SUCCESS", 200, res);
});

// 更新管理员头像，昵称
router.put("/modifyUserInfor", new Auth().m, async (ctx) => {
  const { _id, avatarUrl, nickname } = ctx.request.body;
  ModifyUserInfor(_id, avatarUrl, nickname);
  const res = await modelAdministrator.updateOne(
    { _id },
    { avatarUrl, nickname }
  );
  ctx.send();
});

// 上传每日推荐
router.post("/dailyRecom", new Auth().m, async (ctx) => {
  const { imageUrl, title, address, color } = ctx.request.body;
  DailyRecom(imageUrl, title, address, color);
  await modelDairecom.create({
    imageUrl,
    title,
    address,
    color,
  });
  ctx.send("SUCCESS", 200, { message: "上传成功" });
});

// 导入省市到数据库
router.get("/insert-database", new Auth().m, async (ctx) => {
  try {
    // 读取china.json文件
    const chinaData = JSON.parse(
      fs.readFileSync(path.join(process.cwd(), "china.json"), "utf8")
    );
    console.log(chinaData[10].citys);
    await modelProvince.insertMany(chinaData);
    ctx.send("SUCCESS", 200, { message: "省市数据导入成功" });
  } catch (error) {
    console.error("导入省市数据失败:", error);
    ctx.send("导入省市数据失败", 500);
  }
});

// 搜索省市数据
router.get("/china-data", new Auth().m, async (ctx) => {
  const { keywords } = ctx.request.query;
  SearchTravel(keywords);
  if (keywords.trim() === "") {
    ctx.send("SUCCESS", 200, []);
    return false;
  }
  const regex = new RegExp(keywords, "i");
  // aggregate:聚合查询
  // $match:用来查询
  const res = await modelProvince.aggregate([
    {
      $match: {
        $or: [{ provinceName: regex }, { "citys.cityName": regex }],
      },
    },
    {
      $project: {
        // 表示不返回_id字段
        _id: 0,
        provinceName: 1,
        citys: {
          $filter: {
            input: "$citys", //表示对哪个字段进行过滤
            as: "city", //指定变量值
            cond: {
              // 进行逻辑处理
              $or: [
                // 匹配城市名
                {
                  $regexMatch: {
                    input: "$$city.cityName",
                    regex: regex,
                  },
                },
                // 匹配省份名
                {
                  $regexMatch: {
                    input: "$provinceName",
                    regex: regex,
                  },
                },
              ],
            },
          },
        },
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 获取每日推荐
router.get("/gainDailyRecom", new Auth().m, async (ctx) => {
  const { page } = ctx.request.query;
  Resreturn(page);
  const res = await modelDairecom
    .find({}, { timestamp: false })
    .sort({ timestamp: -1 })
    .skip((page - 1) * 6)
    .limit(6);

  // 获取数据总条数
  const count = await modelDairecom.countDocuments();
  const resData = {
    data: res,
    count,
  };
  ctx.send("SUCCESS", 200, resData);
});

// 删除每日推荐
router.delete("/deleteDailyRecom", new Auth().m, async (ctx) => {
  const { _id } = ctx.request.body;
  CompanionDetails(_id);
  await modelDairecom.deleteOne({ _id });
  ctx.send("SUCCESS", 200, { message: "删除成功" });
});

// 获取所有用户的游记，用作关联推荐
router.get("/allUserTravel", new Auth().m, async (ctx) => {
  const { page } = ctx.request.query;
  Resreturn(page);
  const res = await modelArticle.aggregate([
    { $sort: { timestamp: -1 } },
    { $skip: (page - 1) * 10 },
    { $limit: 10 },
    looKup().model_user,
    {
      $project: {
        _id: 1,
        title: 1,
        address: 1,
        time: 1,
        "author_data.nickname": 1,
      },
    },
  ]);

  // 获取游记总条数
  const count = await modelArticle.countDocuments();
  const resObj = {
    data: res,
    count,
  };
  ctx.send("SUCCESS", 200, resObj);
});
// 删除游记
router.delete("/deleteUserTravel", new Auth().m, async (ctx) => {
  const { _id } = ctx.request.body;
  CompanionDetails(_id);
  await modelArticle.deleteOne({ _id });
  ctx.send("SUCCESS", 200, { message: "删除成功" });
});

// 提交四个推荐
router.post("/uploadFourTravel", new Auth().m, async (ctx) => {
  const { imageUrl, travel_id } = ctx.request.body;
  UploadFourTravel(imageUrl, travel_id);
  await modelFourTravel.create({
    imageUrl,
    travel_id,
  });
  ctx.send("SUCCESS", 200, { message: "提交成功" });
});

// 获取四个推荐
router.get("/gainRecomTravel", new Auth().m, async (ctx) => {
  const res = await modelFourTravel.aggregate([
    { $sort: { timestamp: -1 } },
    looKupRecommend().model_Article,
    looKupRecommend().model_reco_user,
    { $unwind: "$articleData" },
    { $unwind: "$userData" },
    {
      $project: {
        _id: 1,
        imageUrl: 1,
        time: 1,
        travel_id: 1,
        articleTime: "$articleData.time",
        nickname: "$userData.nickname",
        title: "$articleData.title",
      },
    },
  ]);
  ctx.send("SUCCESS", 200, res);
});

// 修改更新四个游记
router.put("/modifyRecomTravel", new Auth().m, async (ctx) => {
  const { _id, imageUrl, travel_id } = ctx.request.body;
  ModifyRecomTravel(_id, imageUrl, travel_id);
  await modelFourTravel.findOneAndUpdate({ _id }, { imageUrl, travel_id });
  ctx.send("SUCCESS", 200, { message: "修改成功" });
});

// 删除四个游记
router.delete("/deleteRecomTravel", new Auth().m, async (ctx) => {
  const { _id } = ctx.request.body;
  CompanionDetails(_id);
  await modelFourTravel.deleteMany({ _id });
  ctx.send("SUCCESS", 200, { message: "删除成功" });
});

//游记管理：获取全部游记
router.get("/travelManaGement", new Auth().m, async (ctx) => {
  const { page } = ctx.request.query;
  Resreturn(page);
  const res = await modelArticle.aggregate([
    { $sort: { timestamp: -1 } },
    { $skip: (page - 1) * 10 },
    { $limit: 10 },
    looKup().model_user,
    {
      $project: {
        _id: 1,
        title: 1,
        content: 1,
        image: 1,
        videoUrl: 1,
        fileType: 1,
        city: 1,
        address: 1,
        province: 1,
        time: 1,
        cover_image: 1,
        "author_data.avatarUrl": 1,
        "author_data.nickname": 1,
      },
    },
  ]);
  // 获取游记总条数
  const count = await modelArticle.countDocuments();
  const resObj = {
    data: res,
    count,
  };
  ctx.send("SUCCESS", 200, resObj);
});

// 用户管理：获取所有用户信息
router.get("/allUserInfor", new Auth().m, async (ctx) => {
  const { page } = ctx.request.query;
  Resreturn(page);
  const res = await modelUser.aggregate([
    { $skip: (page - 1) * 10 },
    { $limit: 10 },
    {
      $lookup: {
        // 关联游记表，获取游记数量
        from: modelArticle.collection.name,
        localField: "uid",
        foreignField: "author_uid",
        as: "articleQuantity",
      },
    },
    {
      $lookup: {
        // 关联关注表，获取粉丝数
        from: modelConcern.collection.name,
        localField: "uid",
        foreignField: "im_concerned_uid",
        as: "concernQuantity",
      },
    },
    {
      $project: {
        _id: 1,
        avatarUrl: 1,
        nickname: 1,
        uid: 1,
        email: 1,
        // 计算粉丝数量
        "concernQuantity":{
          $size:"$concernQuantity"
        },
        // 计算游记数量
        "articleQuantity":{
          $size:"$articleQuantity"
        }
      },
    },
  ]);
  const count = await modelUser.countDocuments();
  const resObj = {
    data: res,
    count,
  };
  ctx.send("SUCCESS", 200, resObj);
});

module.exports = router.routes();
